// Copyright (C) 2025, ZWSOFT Co., LTD.(Guangzhou)
// Licensed under the MIT License. See LICENSE in the project root for license information.

using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using TestClient.Domain;
using TestClient.ViewModel.Util;

namespace TestClient.ViewModel;

public partial class HomeViewModel(VFAdapterWrapper wrapper, ISnackNotifyService notifyService) : ObservableObject
{
    [ObservableProperty]
    [NotifyCanExecuteChangedFor(nameof(LoadDllCommand))]
    [NotifyCanExecuteChangedFor(nameof(UnloadDllCommand))]
    public string dllPath = "";

    [ObservableProperty]
    [NotifyCanExecuteChangedFor(nameof(LoadDllCommand))]
    [NotifyCanExecuteChangedFor(nameof(UnloadDllCommand))]
    public bool isRunning = false;

    private bool CanLoad => !IsRunning && !wrapper.IsLoaded && !string.IsNullOrWhiteSpace(DllPath);
    private bool CanUnload => !IsRunning && wrapper.IsLoaded && !string.IsNullOrWhiteSpace(DllPath);

    [RelayCommand(CanExecute = nameof(CanLoad))]
    private async Task LoadDllAsync()
    {
        IsRunning = true;
        await Task.Run(() => wrapper.LoadLibrary(DllPath));
        IsRunning = false;
        notifyService.PushMessage("DLL load succeeded");
    }

    [RelayCommand(CanExecute = nameof(CanUnload))]
    private async Task UnloadDllAsync()
    {
        IsRunning = true;
        await Task.Run(() => wrapper.UnloadLibrary());
        IsRunning = false;
        notifyService.PushMessage("DLL unload succeeded");
    }

    [RelayCommand]
    private void OpenFile()
    {
        DllPath = DialogUtil.ShowOpenFileDialog("VFAdapter", ".dll", "DLL file (.dll)|*.dll") ?? DllPath;
    }
}
